package com.pig4cloud.pig.wzjiang.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.wzjiang.entity.WzColumnEntity;
import com.pig4cloud.pig.wzjiang.feign.RemoteColumnService;
import com.pig4cloud.pig.wzjiang.service.WzColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 栏目表
 *
 * @author jiang
 * @date 2025-07-24 09:05:46
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/wzColumn" )
@Tag(description = "wzColumn" , name = "栏目表管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class WzColumnController {

    private final WzColumnService wzColumnService;

	private final RemoteColumnService remoteColumnService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param wzColumn 栏目表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('pig_wzColumn_view')" )
	public R getWzColumnPage(@ParameterObject Page<WzColumnEntity> page,
							 @ParameterObject WzColumnEntity wzColumn) {
		LambdaQueryWrapper<WzColumnEntity> wrapper = Wrappers.lambdaQuery();

		// 动态条件：如果传了 columnId，就查指定栏目；否则查所有一级栏目（parentId = 0）
		if (wzColumn.getColumnId() != null) {
			wrapper.eq(WzColumnEntity::getColumnId, wzColumn.getColumnId());
		} else {
			wrapper.eq(WzColumnEntity::getParentId, 0L);
		}

		// 分页查询一级栏目
		Page<WzColumnEntity> pageResult = wzColumnService.page(page, wrapper);

		// 获取所有一级栏目 ID
		List<Long> parentIds = pageResult.getRecords()
				.stream()
				.map(WzColumnEntity::getColumnId)
				.collect(Collectors.toList());

		if (!parentIds.isEmpty()) {
			// 一次性查出所有子栏目
			List<WzColumnEntity> allChildren = wzColumnService.list(
					Wrappers.<WzColumnEntity>lambdaQuery()
							.in(WzColumnEntity::getParentId, parentIds)
			);

			// 按 parentId 分组
			Map<Long, List<WzColumnEntity>> childrenMap = allChildren.stream()
					.collect(Collectors.groupingBy(WzColumnEntity::getParentId));

			// 设置子栏目
			pageResult.getRecords().forEach(entity ->
					entity.setChildren(childrenMap.getOrDefault(entity.getColumnId(), Collections.emptyList()))
			);
		}

		return R.ok(pageResult);
	}


    /**
     * 通过id查询栏目表
     * @param columnId id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{columnId}" )
    @PreAuthorize("@pms.hasPermission('pig_wzColumn_view')" )
    public R getById(@PathVariable("columnId" ) Long columnId) {
        return R.ok(wzColumnService.getById(columnId));
    }

    /**
     * 新增栏目表
     * @param wzColumn 栏目表
     * @return R
     */
    @Operation(summary = "新增栏目表" , description = "新增栏目表" )
    @SysLog("新增栏目表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('pig_wzColumn_add')" )
    public R save(@RequestBody WzColumnEntity wzColumn) {
		//项目名称不重复
		if (wzColumnService.count(Wrappers.<WzColumnEntity>lambdaQuery().eq(WzColumnEntity::getColumnName, wzColumn.getColumnName())) > 0) {
			return R.failed("栏目名称已存在");
		}
        return R.ok(wzColumnService.save(wzColumn));
    }

    /**
     * 修改栏目表
     * @param wzColumn 栏目表
     * @return R
     */
    @Operation(summary = "修改栏目表" , description = "修改栏目表" )
    @SysLog("修改栏目表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('pig_wzColumn_edit')" )
    public R updateById(@RequestBody WzColumnEntity wzColumn) {
		//项目名称不重复
		if (wzColumnService.count(Wrappers.<WzColumnEntity>lambdaQuery().
				eq(WzColumnEntity::getColumnName, wzColumn.getColumnName()).ne(WzColumnEntity::getColumnId, wzColumn.getColumnId())) > 0) {
			return R.failed("栏目名称已存在");
		}
        return R.ok(wzColumnService.updateById(wzColumn));
    }

    /**
     * 通过id删除栏目表
     * @param id columnId
     * @return R
     */
    @Operation(summary = "通过id删除栏目表" , description = "通过id删除栏目表" )
    @SysLog("通过id删除栏目表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('pig_wzColumn_del')" )
    public R removeById(@PathVariable("id" ) Long id) {
		//逻辑删除
		//如果为一级栏目，则删除所有子栏目
		WzColumnEntity wzColumn = wzColumnService.getById(id);
		if (wzColumn.getParentId() == 0) {
			List<WzColumnEntity> children = wzColumnService.list(
					Wrappers.<WzColumnEntity>lambdaQuery().eq(WzColumnEntity::getParentId, id));
			if (CollUtil.isNotEmpty(children)) {
				for (WzColumnEntity child : children) {
					//如果表下没有文章，删除子栏目
					if (remoteColumnService.getWzArticleByColumnId(child.getColumnId()).size() != 0) {
						return R.failed("子栏目下有文章");
					}
					wzColumnService.removeById(child.getColumnId());
				}
			}
		}else{
			//如果表下没有文章，删除栏目
			if (remoteColumnService.getWzArticleByColumnId(wzColumn.getColumnId()).size() != 0) {
				return R.failed("该栏目下有文章");
			}
		}
		return R.ok(wzColumnService.removeById(id));
    }

    /**
     * 导出excel 表格
     * @param wzColumn 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('pig_wzColumn_export')" )
    public List<WzColumnEntity> export(WzColumnEntity wzColumn,Long[] ids) {
        return wzColumnService.list(Wrappers.lambdaQuery(wzColumn).in(ArrayUtil.isNotEmpty(ids), WzColumnEntity::getColumnId, ids));
    }
	/**
	 * 隐藏/显示栏目
	 * @param columnId 栏目ID
	 * @param visible 是否显示
	 * @return R
	 */
	@Operation(summary = "隐藏/显示栏目" , description = "隐藏/显示栏目" )
	@SysLog("隐藏/显示栏目" )
	@PutMapping("/visible/{columnId}")
	@PreAuthorize("@pms.hasPermission('pig_wzColumn_edit')" )
	public R visible(@PathVariable("columnId") Long columnId, @RequestParam("visible") String visible) {
		WzColumnEntity wzColumn = wzColumnService.getById(columnId);
		if (Objects.isNull(wzColumn)) {
			return R.failed("栏目不存在");
		}
		wzColumn.setVisible(visible);
		//判断是否有子栏目
		if (visible.equals("1")) {
			List<WzColumnEntity> children =
					wzColumnService.list
							(Wrappers.<WzColumnEntity>lambdaQuery().eq(WzColumnEntity::getParentId, columnId));
			if (CollUtil.isNotEmpty(children)) {
				for (WzColumnEntity child : children) {
					child.setVisible(visible);
					wzColumnService.updateById(child);
				}
			}
		}
		//二级栏目不能单独显示
		if (wzColumn.getParentId() != 0 && visible.equals("0")) {
			WzColumnEntity parent = wzColumnService.getById(wzColumn.getParentId());
			if (parent.getVisible().equals("1")) {
			return R.failed("二级栏目不能单独显示");
			}
		}
		return R.ok(wzColumnService.updateById(wzColumn));
	}
	@Operation(summary = "获得所有二级栏目" , description = "获得所有二级栏目" )
	@GetMapping("/soncolumn" )
	@PreAuthorize("@pms.hasPermission('pig_wzColumn_view')" )
	public R getSonColumn() {
		LambdaQueryWrapper<WzColumnEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.ne(WzColumnEntity::getParentId, 0L)
				.eq(WzColumnEntity::getCloumnType, "0")
				.eq(WzColumnEntity::getVisible, "0");
		List<WzColumnEntity> list = wzColumnService.list(wrapper);
		return R.ok(list);
	}

}